package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;


import static com.sky.entity.Orders.*;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;


//    @Scheduled(cron = "0/5 * * * * ?  ")
//    public void TaskTest(){
//
//        log.info("当前时间，{}",LocalDateTime.now());
//    }

    //超时未支付订单自动取消

    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    //  @Scheduled(cron = "0/5 * * * * ?  ")
    public void OrderTimeOut() {

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime fifteenMinutesAgo = now.minus(Duration.ofMinutes(15));


        List<Orders> orders = orderMapper.OrderTimeOut(PENDING_PAYMENT, fifteenMinutesAgo);
        if (orders != null && !orders.isEmpty()) {

            orders.forEach(orders1 -> {
                orders1.setCancelReason("订单超时未支付，已自动取消");
                orders1.setCancelTime(LocalDateTime.now());
                orders1.setStatus(CANCELLED);
                orderMapper.update(orders1);
            });
        }
    }


    //  已完成但仍处于派送中状态的订单，在凌晨一点统一修改状态已完成
    @Scheduled(cron = "0 0 1 * * ? ")
    // @Scheduled(cron = "1/5 * * * * ?  ")
    public void updateStatus() {
        List<Orders> orders = orderMapper.OrderTimeOut(DELIVERY_IN_PROGRESS, LocalDateTime.now());
        if (orders != null && orders.size() > 0) {

            orders.forEach(orders1 -> {
                orders1.setStatus(CANCELLED);
                orderMapper.update(orders1);
            });
        }

    }

}
